#include "include/MiniDatabase.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <regex>
#include <stdexcept>
#include "include/ILogger.h"

namespace Tool
{
// Condition类实现
Condition::Condition(const std::string& field, ConditionOperator op, const Variant& value)
    : m_field(field)
    , m_op(op)
    , m_value(value)
    , m_isComposite(false)
{
}

Condition::Condition(const std::vector<Condition>& conditions, LogicalOperator logicalOp)
    : m_conditions(conditions)
    , m_logicalOp(logicalOp)
    , m_isComposite(true)
{
}

bool Condition::Evaluate(const VariantHash& record) const
{
    if (m_isComposite)
    {
        if (m_conditions.empty())
        {
            return true;
        }
        
        bool result = m_conditions[0].Evaluate(record);
        
        for (size_t i = 1; i < m_conditions.size(); ++i)
        {
            bool current = m_conditions[i].Evaluate(record);
            
            if (m_logicalOp == LogicalOperator::And)
            {
                result = result && current;
                if (!result) break; // 短路求值
            }
            else
            {
                result = result || current;
                if (result) break; // 短路求值
            }
        }
        
        return result;
    }
    else
    {
        // 检查字段是否存在
        auto it = record.find(m_field);
        if (it == record.end())
        {
            return false;
        }
        
        const Variant& fieldValue = it->second;
        
        // 处理NULL情况
        if (fieldValue.Type() == VariantType::None)
        {
            return (m_op == ConditionOperator::IsNull);
        }
        
        switch (m_op)
        {
            case ConditionOperator::Equals:
                return fieldValue == m_value;
                
            case ConditionOperator::NotEquals:
                return fieldValue != m_value;
                
            case ConditionOperator::GreaterThan:
                if (fieldValue.Type() == VariantType::Int && m_value.Type() == VariantType::Int)
                    return fieldValue.ToInt() > m_value.ToInt();
                if (fieldValue.Type() == VariantType::Float && m_value.Type() == VariantType::Float)
                    return fieldValue.ToFloat() > m_value.ToFloat();
                if (fieldValue.Type() == VariantType::Double && m_value.Type() == VariantType::Double)
                    return fieldValue.ToDouble() > m_value.ToDouble();
                return false;
                
            case ConditionOperator::LessThan:
                if (fieldValue.Type() == VariantType::Int && m_value.Type() == VariantType::Int)
                    return fieldValue.ToInt() < m_value.ToInt();
                if (fieldValue.Type() == VariantType::Float && m_value.Type() == VariantType::Float)
                    return fieldValue.ToFloat() < m_value.ToFloat();
                if (fieldValue.Type() == VariantType::Double && m_value.Type() == VariantType::Double)
                    return fieldValue.ToDouble() < m_value.ToDouble();
                return false;
                
            case ConditionOperator::GreaterOrEqual:
                if (fieldValue.Type() == VariantType::Int && m_value.Type() == VariantType::Int)
                    return fieldValue.ToInt() >= m_value.ToInt();
                if (fieldValue.Type() == VariantType::Float && m_value.Type() == VariantType::Float)
                    return fieldValue.ToFloat() >= m_value.ToFloat();
                if (fieldValue.Type() == VariantType::Double && m_value.Type() == VariantType::Double)
                    return fieldValue.ToDouble() >= m_value.ToDouble();
                return false;
                
            case ConditionOperator::LessOrEqual:
                if (fieldValue.Type() == VariantType::Int && m_value.Type() == VariantType::Int)
                    return fieldValue.ToInt() <= m_value.ToInt();
                if (fieldValue.Type() == VariantType::Float && m_value.Type() == VariantType::Float)
                    return fieldValue.ToFloat() <= m_value.ToFloat();
                if (fieldValue.Type() == VariantType::Double && m_value.Type() == VariantType::Double)
                    return fieldValue.ToDouble() <= m_value.ToDouble();
                return false;
                
            case ConditionOperator::Like:
                if (fieldValue.Type() == VariantType::String && m_value.Type() == VariantType::String)
                {
                    // 简单的Like实现，仅支持%通配符
                    std::string pattern = m_value.ToString();
                    std::string str = fieldValue.ToString();
                    
                    // 转换为正则表达式
                    std::string regexPattern;
                    for (char c : pattern)
                    {
                        if (c == '%')
                            regexPattern += ".*";
                        else if (std::ispunct(static_cast<unsigned char>(c)))
                            regexPattern += "\\" + std::string(1, c);
                        else
                            regexPattern += c;
                    }
                    
                    return std::regex_match(str, std::regex(regexPattern));
                }
                return false;
                
            case ConditionOperator::In:
                if (m_value.Type() == VariantType::Vector)
                {
                    for (const auto& val : m_value.ToVector())
                    {
                        if (fieldValue == val)
                            return true;
                    }
                }
                return false;
                
            case ConditionOperator::NotIn:
                if (m_value.Type() == VariantType::Vector)
                {
                    for (const auto& val : m_value.ToVector())
                    {
                        if (fieldValue == val)
                            return false;
                    }
                    return true;
                }
                return false;
                
            case ConditionOperator::IsNull:
                return fieldValue.Type() == VariantType::None;
                
            case ConditionOperator::IsNotNull:
                return fieldValue.Type() != VariantType::None;
                
            default:
                return false;
        }
    }
}

// ConditionBuilder类实现
Condition ConditionBuilder::Equals(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::Equals, value);
}

Condition ConditionBuilder::NotEquals(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::NotEquals, value);
}

Condition ConditionBuilder::GreaterThan(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::GreaterThan, value);
}

Condition ConditionBuilder::LessThan(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::LessThan, value);
}

Condition ConditionBuilder::GreaterOrEqual(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::GreaterOrEqual, value);
}

Condition ConditionBuilder::LessOrEqual(const std::string& field, const Variant& value)
{
    return Condition(field, ConditionOperator::LessOrEqual, value);
}

Condition ConditionBuilder::Like(const std::string& field, const std::string& pattern)
{
    return Condition(field, ConditionOperator::Like, Variant(pattern));
}

Condition ConditionBuilder::In(const std::string& field, const std::vector<Variant>& values)
{
    return Condition(field, ConditionOperator::In, Variant(values));
}

Condition ConditionBuilder::NotIn(const std::string& field, const std::vector<Variant>& values)
{
    return Condition(field, ConditionOperator::NotIn, Variant(values));
}

Condition ConditionBuilder::IsNull(const std::string& field)
{
    return Condition(field, ConditionOperator::IsNull, Variant());
}

Condition ConditionBuilder::IsNotNull(const std::string& field)
{
    return Condition(field, ConditionOperator::IsNotNull, Variant());
}

Condition ConditionBuilder::Combine(const std::vector<Condition>& conditions, LogicalOperator op)
{
    return Condition(conditions, op);
}

Condition ConditionBuilder::And(const std::vector<Condition>& conditions)
{
    return Combine(conditions, LogicalOperator::And);
}

Condition ConditionBuilder::Or(const std::vector<Condition>& conditions)
{
    return Combine(conditions, LogicalOperator::Or);
}

// Table类实现
Table::Table(const std::string& name, const std::vector<FieldDefinition>& fields)
    : m_name(name)
    , m_fields(fields)
    , m_primaryKey("")
{
    // 查找主键
    for (const auto& field : fields)
    {
        if (field.m_isPrimaryKey)
        {
            if (!m_primaryKey.empty())
            {
                LOG_WARN("表 %s 有多个主键定义，仅使用第一个", m_name.c_str());
                break;
            }
            m_primaryKey = field.m_name;
        }
    }

    for (const auto& field : fields) 
    {
        m_fieldNames.insert(field.m_name);
    }
}

const std::string& Table::GetName() const
{
    return m_name;
}

const std::vector<FieldDefinition>& Table::GetFields() const
{
    return m_fields;
}

bool Table::ValidateRecord(const VariantHash& record, bool isInsert) const
{
    // 检查所有非空字段是否都有值
    for (const auto& field : m_fields)
    {
        auto it = record.find(field.m_name);
        
        // 检查非空字段
        if (!field.m_isNullable && (it == record.end() || it->second.Type() == VariantType::None))
        {
            LOG_ERROR("字段 %s 不允许为空", field.m_name.c_str());
            return false;
        }
        
        // 检查主键（仅插入时）
        if (isInsert && field.m_isPrimaryKey)
        {
            if (it == record.end() || it->second.Type() == VariantType::None)
            {
                LOG_ERROR("主键字段 %s 不允许为空", field.m_name.c_str());
                return false;
            }
            
            // 检查主键唯一性
            if (FindPrimaryKeyIndex(it->second) != -1)
            {
                LOG_ERROR("主键 %s 的值已存在", field.m_name.c_str());
                return false;
            }
        }
        
        // 检查字段类型
        if (it != record.end() && it->second.Type() != VariantType::None)
        {
            bool typeValid = false;
            switch (field.m_type)
            {
                case FieldType::Int:
                    typeValid = (it->second.Type() == VariantType::Int || 
                               it->second.Type() == VariantType::Long ||
                               it->second.Type() == VariantType::UInt ||
                               it->second.Type() == VariantType::ULong);
                    break;
                    
                case FieldType::Float:
                    typeValid = (it->second.Type() == VariantType::Float);
                    break;
                    
                case FieldType::Double:
                    typeValid = (it->second.Type() == VariantType::Double ||
                               it->second.Type() == VariantType::Float);
                    break;
                    
                case FieldType::String:
                    typeValid = (it->second.Type() == VariantType::String);
                    break;
                    
                case FieldType::Bool:
                    typeValid = (it->second.Type() == VariantType::Bool);
                    break;
                    
                case FieldType::Binary:
                    typeValid = (it->second.Type() == VariantType::Binary);
                    break;
                    
                default:
                    typeValid = true;
            }
            
            if (!typeValid)
            {
                LOG_ERROR("字段 %s 的类型不匹配", field.m_name.c_str());
                return false;
            }
        }
    }
    
    // 检查记录中是否有不存在的字段
    for (const auto& pair : record)
    {
        if (m_fieldNames.find(pair.first) == m_fieldNames.end())
        {
            LOG_WARN("记录包含表 %s 中不存在的字段 %s", m_name.c_str(), pair.first.c_str());
            return false;
        }
    }
    
    return true;
}

int Table::FindPrimaryKeyIndex(const Variant& value) const
{
    if (m_primaryKey.empty())
    {
        return -1; // 没有主键
    }
    
    auto it = m_primaryKeyIndex.find(value);
    return (it != m_primaryKeyIndex.end()) ? static_cast<int>(it->second) : -1;
}

Variant Table::ConvertToFieldType(const Variant& value, FieldType type) const
{
    switch (type)
    {
        case FieldType::Int:
            return Variant(static_cast<int>(value.ToLong()));
            
        case FieldType::Float:
            return Variant(static_cast<float>(value.ToDouble()));
            
        case FieldType::Double:
            return Variant(value.ToDouble());
            
        case FieldType::String:
            return Variant(value.ToString());
            
        case FieldType::Bool:
            return Variant(value.ToBool());
            
        default:
            return value;
    }
}

bool Table::Insert(const VariantHash& record)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    // 验证记录
    if (!ValidateRecord(record))
    {
        LOG_ERROR("插入记录失败，记录验证不通过");
        return false;
    }
    
    // 创建新记录，包含默认值
    VariantHash newRecord;
    for (const auto& field : m_fields)
    {
        auto it = record.find(field.m_name);
        if (it != record.end() && it->second.Type() != VariantType::None)
        {
            newRecord[field.m_name] = ConvertToFieldType(it->second, field.m_type);
        }
        else if (field.m_defaultValue.Type() != VariantType::None)
        {
            newRecord[field.m_name] = field.m_defaultValue;
        }
        else
        {
            newRecord[field.m_name] = Variant();
        }
    }

    if (!m_primaryKey.empty()) 
    {
        auto pkValue = newRecord[m_primaryKey];
        m_primaryKeyIndex[pkValue] = m_records.size();  // 索引为新记录的位置
    }
    
    m_records.push_back(newRecord);
    return true;
}

std::vector<VariantHash> Table::Query(
    const std::vector<std::string>& fields,
    const Condition& condition,
    const std::map<std::string, SortOrder>& orderBy,
    size_t limit,
    size_t offset
)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    // 筛选记录
    std::vector<VariantHash> result;
    for (const auto& record : m_records)
    {
        if (condition.Evaluate(record))
        {
            result.push_back(record);
        }
    }
    
    // 排序
    if (!orderBy.empty())
    {
        std::sort(result.begin(), result.end(), 
                  [&orderBy](const VariantHash& a, const VariantHash& b)
        {
            for (const auto& pair : orderBy)
            {
                const std::string& field = pair.first;
                SortOrder order = pair.second;
                
                auto itA = a.find(field);
                auto itB = b.find(field);
                
                // 处理字段不存在的情况
                if (itA == a.end() || itB == b.end())
                {
                    continue;
                }
                
                const Variant& valA = itA->second;
                const Variant& valB = itB->second;
                
                // 比较值
                bool lessThan = false;
                
                if (valA.Type() == VariantType::Int && valB.Type() == VariantType::Int)
                {
                    lessThan = valA.ToInt() < valB.ToInt();
                }
                else if (valA.Type() == VariantType::Float && valB.Type() == VariantType::Float)
                {
                    lessThan = valA.ToFloat() < valB.ToFloat();
                }
                else if (valA.Type() == VariantType::Double && valB.Type() == VariantType::Double)
                {
                    lessThan = valA.ToDouble() < valB.ToDouble();
                }
                else if (valA.Type() == VariantType::String && valB.Type() == VariantType::String)
                {
                    lessThan = valA.ToString() < valB.ToString();
                }
                else if (valA.Type() == VariantType::Bool && valB.Type() == VariantType::Bool)
                {
                    lessThan = !valA.ToBool() && valB.ToBool();
                }
                
                if (order == SortOrder::Ascending)
                {
                    if (lessThan) return true;
                    if (!lessThan && !(valA == valB)) return false;
                }
                else
                {
                    if (!lessThan && !(valA == valB)) return true;
                    if (lessThan) return false;
                }
            }
            
            return false;
        });
    }
    
    // 应用偏移量和限制
    if (offset > 0 && offset < result.size())
    {
        result = std::vector<VariantHash>(result.begin() + offset, result.end());
    }
    
    if (limit > 0 && limit < result.size())
    {
        result.resize(limit);
    }
    
    // 筛选字段
    if (!fields.empty())
    {
        std::vector<VariantHash> filteredResult;
        filteredResult.reserve(result.size());
        
        for (const auto& record : result)
        {
            VariantHash filteredRecord;
            
            for (const auto& field : fields)
            {
                auto it = record.find(field);
                if (it != record.end())
                {
                    filteredRecord[field] = it->second;
                }
                else
                {
                    LOG_WARN("查询中包含不存在的字段 %s", field.c_str());
                    filteredRecord[field] = Variant();
                }
            }
            
            filteredResult.push_back(filteredRecord);
        }
        
        result = filteredResult;
    }
    
    return result;
}

size_t Table::Update(const VariantHash& updates,const Condition& condition)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    if (updates.empty())
    {
        LOG_WARN("没有提供要更新的字段");
        return 0;
    }
    
    // 验证更新字段
    for (const auto& pair : updates)
    {
        if (m_fieldNames.find(pair.first) == m_fieldNames.end())
        {
            LOG_ERROR("更新失败，字段 %s 不存在", pair.first.c_str());
            return 0;
        }
        
        // 检查主键是否被更新
        if (!m_primaryKey.empty() && pair.first == m_primaryKey)
        {
            // 检查新主键值是否已存在
            int index = FindPrimaryKeyIndex(pair.second);
            if (index != -1)
            {
                LOG_ERROR("更新失败，主键 %s 的新值已存在", pair.first.c_str());
                return 0;
            }
        }
    }
    
    // 执行更新
    size_t updatedCount = 0;
    bool primaryKeyUpdated = !m_primaryKey.empty() && updates.count(m_primaryKey) > 0;

    for (size_t i = 0; i < m_records.size(); ++i)
    {
        auto& record = m_records[i];
        if (condition.Evaluate(record))
        {
            // 创建临时记录用于验证
            VariantHash tempRecord = record;
            for (const auto& pair : updates)
            {
                tempRecord[pair.first] = pair.second;
            }

            // 验证更新后的记录
            if (ValidateRecord(tempRecord, false))
            {
                // 若更新了主键，先移除旧索引
                if (primaryKeyUpdated)
                {
                    auto oldPkValue = record[m_primaryKey];
                    m_primaryKeyIndex.erase(oldPkValue);
                }

                // 应用更新
                for (const auto& pair : updates)
                {
                    // 查找字段定义以进行类型转换
                    for (const auto& field : m_fields)
                    {
                        if (pair.first == field.m_name)
                        {
                            record[pair.first] = ConvertToFieldType(pair.second, field.m_type);
                            break;
                        }
                    }
                }

                // 更新主键索引
                if (primaryKeyUpdated)
                {
                    auto newPkValue = record[m_primaryKey];
                    m_primaryKeyIndex[newPkValue] = i;
                }

                updatedCount++;
            }
            else
            {
                LOG_WARN("记录更新失败，验证不通过");
            }
        }
    }
    
    return updatedCount;
}

size_t Table::Remove(const Condition& condition)
{
    std::lock_guard<std::mutex> lock(m_mutex);

    size_t initialCount = m_records.size();
    std::vector<size_t> toRemove;

    // 先收集要删除的记录索引
    for (size_t i = 0; i < m_records.size(); ++i)
    {
        if (condition.Evaluate(m_records[i]))
        {
            toRemove.push_back(i);
        }
    }

    // 从后往前删除，避免索引偏移
    std::sort(toRemove.rbegin(), toRemove.rend());
    for (size_t idx : toRemove)
    {
        // 移除主键索引
        if (!m_primaryKey.empty())
        {
            auto pkValue = m_records[idx][m_primaryKey];
            m_primaryKeyIndex.erase(pkValue);
        }

        m_records.erase(m_records.begin() + idx);
    }

    // 更新剩余记录的主键索引
    if (!m_primaryKey.empty() && !toRemove.empty())
    {
        // 只在有删除且存在主键时才更新
        m_primaryKeyIndex.clear();
        for (size_t i = 0; i < m_records.size(); ++i)
        {
            auto pkValue = m_records[i][m_primaryKey];
            m_primaryKeyIndex[pkValue] = i;
        }
    }

    return initialCount - m_records.size();
}

size_t Table::GetRecordCount()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_records.size();
}

void Table::Clear()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_records.clear();
    m_primaryKeyIndex.clear();
}

bool Table::Load(const std::string& filePath)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    try
    {
        Variant data;
        if (!data.DeserializeFromFile(filePath, VariantSerializeType::Binary))
        {
            LOG_ERROR("加载表 %s 失败，无法从文件读取数据", m_name.c_str());
            return false;
        }
        
        if (data.Type() != VariantType::Vector)
        {
            LOG_ERROR("加载表 %s 失败，数据格式不正确", m_name.c_str());
            return false;
        }
        
        m_records = data.RefValue<std::vector<VariantHash>>();

        m_primaryKeyIndex.clear();
        if (!m_primaryKey.empty())
        {
            for (size_t i = 0; i < m_records.size(); ++i)
            {
                auto it = m_records[i].find(m_primaryKey);
                if (it != m_records[i].end())
                {
                    m_primaryKeyIndex[it->second] = i;
                }
            }
        }
        LOG_INFO("成功从 %s 加载表 %s，共 %zu 条记录", filePath.c_str(), m_name.c_str(), m_records.size());
        return true;
    }
    catch (const std::exception& e)
    {
        LOG_ERROR("加载表 %s 失败: %s", m_name.c_str(), e.what());
        return false;
    }
}

bool Table::Save(const std::string& filePath)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    try
    {
        Variant data(m_records);
        if (!data.SerializeToFile(filePath, VariantSerializeType::Binary))
        {
            LOG_ERROR("保存表 %s 失败，无法写入文件", m_name.c_str());
            return false;
        }
        
        LOG_INFO("成功将表 %s 保存到 %s，共 %zu 条记录", filePath.c_str(), m_name.c_str(), m_records.size());
        return true;
    }
    catch (const std::exception& e)
    {
        LOG_ERROR("保存表 %s 失败: %s", m_name.c_str(), e.what());
        return false;
    }
}

// MiniDatabase类实现
MiniDatabase::MiniDatabase(const std::string& filePath)
    : m_filePath(filePath)
    , m_inTransaction(false)
{
    if (!filePath.empty())
    {
        Load(filePath);
    }
}

bool MiniDatabase::Open(const std::string& filePath)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_filePath = filePath;
    return Load(filePath);
}

void MiniDatabase::Close()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    Save();
    m_tables.clear();
    m_filePath.clear();
}

bool MiniDatabase::CreateTable(const std::string& tableName, const std::vector<FieldDefinition>& fields)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    if (TableExists(tableName))
    {
        LOG_ERROR("创建表失败，表 %s 已存在", tableName.c_str());
        return false;
    }
    
    // 检查字段名是否重复
    std::unordered_map<std::string, bool> fieldNames;
    for (const auto& field : fields)
    {
        if (fieldNames.find(field.m_name) != fieldNames.end())
        {
            LOG_ERROR("创建表失败，字段名 %s 重复", field.m_name.c_str());
            return false;
        }
        fieldNames[field.m_name] = true;
    }
    
    m_tables[tableName] = std::make_unique<Table>(tableName, fields);
    LOG_INFO("成功创建表 %s", tableName.c_str());
    
    // 如果不在事务中，立即保存
    if (!m_inTransaction)
    {
        Save();
    }
    
    return true;
}

bool MiniDatabase::DropTable(const std::string& tableName)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    if (!TableExists(tableName))
    {
        LOG_ERROR("删除表失败，表 %s 不存在", tableName.c_str());
        return false;
    }
    
    m_tables.erase(tableName);
    LOG_INFO("成功删除表 %s", tableName.c_str());
    
    // 如果不在事务中，立即保存
    if (!m_inTransaction)
    {
        Save();
    }
    
    return true;
}

bool MiniDatabase::TableExists(const std::string& tableName) const
{
    return m_tables.find(tableName) != m_tables.end();
}

Table* MiniDatabase::GetTable(const std::string& tableName)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    
    auto it = m_tables.find(tableName);
    if (it != m_tables.end())
    {
        return it->second.get();
    }
    
    LOG_ERROR("表 %s 不存在", tableName.c_str());
    return nullptr;
}


ExecuteResult MiniDatabase::Execute(const std::string& sql)
{
    // std::lock_guard<std::mutex> lock(m_mutex);
    return ParseAndExecute(sql);
}

// 辅助函数：去除字符串首尾空格
inline std::string Trim(const std::string& str)
{
    size_t start = str.find_first_not_of(" \t\n\r");
    size_t end = str.find_last_not_of(" \t\n\r");
    return (start == std::string::npos) ? "" : str.substr(start, end - start + 1);
}

// 辅助函数：分割字符串
inline std::vector<std::string> Split(const std::string& str, char delimiter)
{
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter))
    {
        token = Trim(token);
        if (!token.empty())
        {
            tokens.push_back(token);
        }
    }
    return tokens;
}

// 辅助函数：解析值并转换为Variant
inline Variant ParseValue(const std::string& valueStr)
{
    std::string str = Trim(valueStr);

    // 处理字符串类型（带单引号）
    if (str.size() >= 2 && str.front() == '\'' && str.back() == '\'')
    {
        return Variant(str.substr(1, str.size() - 2));
    }

    // 处理布尔类型
    if (str == "true" || str == "TRUE")
        return Variant(true);
    if (str == "false" || str == "FALSE")
        return Variant(false);

    // 处理整数类型
    try
    {
        size_t pos;
        int64_t num = std::stoll(str, &pos);
        if (pos == str.size())
            return Variant(static_cast<int>(num));
    }
    catch (...) {}

    // 处理浮点数类型
    try
    {
        size_t pos;
        double num = std::stod(str, &pos);
        if (pos == str.size())
            return Variant(num);
    }
    catch (...) {}

    // 默认为字符串
    return Variant(str);
}

// 辅助函数：解析条件表达式（简化版）
inline Condition ParseCondition(const std::string& conditionStr)
{
    std::string cond = Trim(conditionStr);
    std::vector<std::string> ops = { "!=", "=", ">=", "<=", ">", "<", "like", "LIKE" };

    for (const auto& op : ops)
    {
        size_t opPos = cond.find(op);
        if (opPos != std::string::npos)
        {
            std::string field = Trim(cond.substr(0, opPos));
            std::string valueStr = Trim(cond.substr(opPos + op.size()));
            Variant value = ParseValue(valueStr);

            if (op == "=")
                return ConditionBuilder::Equals(field, value);
            else if (op == "!=")
                return ConditionBuilder::NotEquals(field, value);
            else if (op == ">")
                return ConditionBuilder::GreaterThan(field, value);
            else if (op == "<")
                return ConditionBuilder::LessThan(field, value);
            else if (op == ">=")
                return ConditionBuilder::GreaterOrEqual(field, value);
            else if (op == "<=")
                return ConditionBuilder::LessOrEqual(field, value);
            else if (op == "like" || op == "LIKE")
                return ConditionBuilder::Like(field, value.ToString());
        }
    }

    // 如果没有找到运算符，返回始终为真的条件（实际应用中应报错）
    LOG_WARN("无法解析条件: %s，将匹配所有记录", conditionStr.c_str());
    return ConditionBuilder::Combine({}, LogicalOperator::And); // 空条件组合默认匹配所有
}

// 解析并执行SELECT语句
inline ExecuteResult ParseSelect(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    std::regex selectRegex(
        R"(^select\s+(.*?)\s+from\s+(\w+)\s*(where\s+(.*?))?\s*(order\s+by\s+(.*?))?\s*(limit\s+(\d+))?$)",
        std::regex::icase
    );

    std::smatch match;
    if (!std::regex_match(sql, match, selectRegex))
    {
        result.m_errorMessage = "SELECT语句格式错误，正确格式: SELECT 字段 FROM 表名 [WHERE 条件] [ORDER BY 字段] [LIMIT 数量]";
        return result;
    }

    // 提取查询字段
    std::string fieldsStr = Trim(match[1]);
    std::vector<std::string> fields;
    if (fieldsStr != "*")
    {
        fields = Split(fieldsStr, ',');
    }

    // 提取表名
    std::string tableName = Trim(match[2]);
    Table* table = db->GetTable(tableName);
    if (!table)
    {
        result.m_errorMessage = "表 " + tableName + " 不存在";
        return result;
    }

    // 提取条件
    Condition condition = ConditionBuilder::Combine({}, LogicalOperator::And); // 匹配所有
    if (!match[4].str().empty())
    {
        condition = ParseCondition(match[4]);
    }

    // 提取排序
    std::map<std::string, SortOrder> orderBy;
    if (!match[6].str().empty())
    {
        std::vector<std::string> orderFields = Split(match[6], ',');
        for (const auto& field : orderFields)
        {
            std::vector<std::string> parts = Split(field, ' ');
            std::string fieldName = parts[0];
            SortOrder order = SortOrder::Ascending;

            if (parts.size() > 1 &&
                (parts[1] == "desc" || parts[1] == "DESC"))
            {
                order = SortOrder::Descending;
            }

            orderBy[fieldName] = order;
        }
    }

    // 提取限制数量
    size_t limit = 0;
    if (!match[8].str().empty())
    {
        limit = std::stoull(match[8].str());
    }

    // 执行查询
    result.m_result = table->Query(fields, condition, orderBy, limit);
    result.m_success = true;
    result.m_affectedRows = result.m_result.size();
    return result;
}

// 解析并执行INSERT语句
inline ExecuteResult ParseInsert(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    // 支持两种格式: INSERT INTO 表名 (字段1,字段2) VALUES (值1,值2)
    // 或 INSERT INTO 表名 SET 字段1=值1,字段2=值2
    std::regex insertRegex1(
        R"(^insert\s+into\s+(\w+)\s*\((.*?)\)\s+values\s*\((.*?)\)$)",
        std::regex::icase
    );
    std::regex insertRegex2(
        R"(^insert\s+into\s+(\w+)\s+set\s+(.*)$)",
        std::regex::icase
    );

    std::smatch match;
    std::string tableName;
    VariantHash record;

    if (std::regex_match(sql, match, insertRegex1))
    {
        tableName = Trim(match[1]);
        std::vector<std::string> fields = Split(match[2], ',');
        std::vector<std::string> values = Split(match[3], ',');

        if (fields.size() != values.size())
        {
            result.m_errorMessage = "字段数量与值数量不匹配";
            return result;
        }

        for (size_t i = 0; i < fields.size(); ++i)
        {
            record[Trim(fields[i])] = ParseValue(values[i]);
        }
    }
    else if (std::regex_match(sql, match, insertRegex2))
    {
        tableName = Trim(match[1]);
        std::vector<std::string> assignments = Split(match[2], ',');

        for (const auto& assign : assignments)
        {
            size_t eqPos = assign.find('=');
            if (eqPos == std::string::npos)
            {
                result.m_errorMessage = "INSERT语句格式错误，字段赋值应为 字段=值";
                return result;
            }

            std::string field = Trim(assign.substr(0, eqPos));
            std::string valueStr = Trim(assign.substr(eqPos + 1));
            record[field] = ParseValue(valueStr);
        }
    }
    else
    {
        result.m_errorMessage = "INSERT语句格式错误，支持: INSERT INTO 表名 (字段) VALUES (值) 或 INSERT INTO 表名 SET 字段=值";
        return result;
    }

    // 执行插入
    Table* table = db->GetTable(tableName);
    if (!table)
    {
        result.m_errorMessage = "表 " + tableName + " 不存在";
        return result;
    }

    result.m_success = table->Insert(record);
    result.m_affectedRows = result.m_success ? 1 : 0;
    if (!result.m_success)
    {
        result.m_errorMessage = "插入记录失败";
    }

    return result;
}

// 解析并执行UPDATE语句
inline ExecuteResult ParseUpdate(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    std::regex updateRegex(
        R"(^update\s+(\w+)\s+set\s+(.*?)\s*(where\s+(.*))?$)",
        std::regex::icase
    );

    std::smatch match;
    if (!std::regex_match(sql, match, updateRegex))
    {
        result.m_errorMessage = "UPDATE语句格式错误，正确格式: UPDATE 表名 SET 字段=值 [WHERE 条件]";
        return result;
    }

    // 提取表名
    std::string tableName = Trim(match[1]);
    Table* table = db->GetTable(tableName);
    if (!table)
    {
        result.m_errorMessage = "表 " + tableName + " 不存在";
        return result;
    }

    // 提取更新字段
    VariantHash updates;
    std::vector<std::string> assignments = Split(match[2], ',');
    for (const auto& assign : assignments)
    {
        size_t eqPos = assign.find('=');
        if (eqPos == std::string::npos)
        {
            result.m_errorMessage = "UPDATE语句格式错误，字段赋值应为 字段=值";
            return result;
        }

        std::string field = Trim(assign.substr(0, eqPos));
        std::string valueStr = Trim(assign.substr(eqPos + 1));
        updates[field] = ParseValue(valueStr);
    }

    // 提取条件
    Condition condition = ConditionBuilder::Combine({}, LogicalOperator::And); // 匹配所有
    if (!match[4].str().empty())
    {
        condition = ParseCondition(match[4]);
    }
    else
    {
        LOG_WARN("UPDATE语句没有WHERE条件，将更新所有记录");
    }

    // 执行更新
    result.m_affectedRows = table->Update(updates, condition);
    result.m_success = true;
    if (result.m_affectedRows == 0)
    {
        result.m_errorMessage = "没有记录被更新";
    }

    return result;
}

// 解析并执行DELETE语句
inline ExecuteResult ParseDelete(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    std::regex deleteRegex(
        R"(^delete\s+from\s+(\w+)\s*(where\s+(.*))?$)",
        std::regex::icase
    );

    std::smatch match;
    if (!std::regex_match(sql, match, deleteRegex))
    {
        result.m_errorMessage = "DELETE语句格式错误，正确格式: DELETE FROM 表名 [WHERE 条件]";
        return result;
    }

    // 提取表名
    std::string tableName = Trim(match[1]);
    Table* table = db->GetTable(tableName);
    if (!table)
    {
        result.m_errorMessage = "表 " + tableName + " 不存在";
        return result;
    }

    // 提取条件
    Condition condition = ConditionBuilder::Combine({}, LogicalOperator::And); // 匹配所有
    if (!match[3].str().empty())
    {
        condition = ParseCondition(match[3]);
    }
    else
    {
        LOG_WARN("DELETE语句没有WHERE条件，将删除所有记录");
    }

    // 执行删除
    result.m_affectedRows = table->Remove(condition);
    result.m_success = true;
    if (result.m_affectedRows == 0)
    {
        result.m_errorMessage = "没有记录被删除";
    }

    return result;
}

// 解析并执行CREATE TABLE语句
inline ExecuteResult ParseCreateTable(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    std::regex createRegex(
        R"(^create\s+table\s+(\w+)\s*\((.*)\)$)",
        std::regex::icase
    );

    std::smatch match;
    if (!std::regex_match(sql, match, createRegex))
    {
        result.m_errorMessage = "CREATE TABLE语句格式错误，正确格式: CREATE TABLE 表名 (字段定义...)";
        return result;
    }

    // 提取表名
    std::string tableName = Trim(match[1]);
    if (db->TableExists(tableName))
    {
        result.m_errorMessage = "表 " + tableName + " 已存在";
        return result;
    }

    // 解析字段定义
    std::vector<FieldDefinition> fields;
    std::vector<std::string> fieldDefs = Split(match[2], ',');

    for (const auto& def : fieldDefs)
    {
        std::string fieldStr = Trim(def);
        std::vector<std::string> parts = Split(fieldStr, ' ');
        if (parts.size() < 2)
        {
            result.m_errorMessage = "字段定义错误: " + fieldStr;
            return result;
        }

        std::string fieldName = parts[0];
        std::string typeStr = parts[1];
        bool isPrimaryKey = false;
        bool isNullable = true;
        Variant defaultValue;

        // 解析字段类型
        FieldType type = FieldType::String; // 默认类型
        if (typeStr == "int" || typeStr == "INT")
            type = FieldType::Int;
        else if (typeStr == "float" || typeStr == "FLOAT")
            type = FieldType::Float;
        else if (typeStr == "double" || typeStr == "DOUBLE")
            type = FieldType::Double;
        else if (typeStr == "bool" || typeStr == "BOOL")
            type = FieldType::Bool;
        else if (typeStr == "string" || typeStr == "VARCHAR")
            type = FieldType::String;

        // 解析约束
        for (size_t i = 2; i < parts.size(); ++i)
        {
            std::string constraint = parts[i];
            if (constraint == "primary" && i + 1 < parts.size() && parts[i + 1] == "key")
            {
                isPrimaryKey = true;
                isNullable = false; // 主键默认为非空
                i++; // 跳过"key"
            }
            else if (constraint == "not" && i + 1 < parts.size() && parts[i + 1] == "null")
            {
                isNullable = false;
                i++; // 跳过"null"
            }
            else if (constraint == "null")
            {
                isNullable = true;
            }
            else if (constraint == "default" && i + 1 < parts.size())
            {
                defaultValue = ParseValue(parts[i + 1]);
                i++; // 跳过默认值
            }
        }

        fields.emplace_back(fieldName, type, isPrimaryKey, isNullable, defaultValue);
    }

    // 创建表
    result.m_success = db->CreateTable(tableName, fields);
    if (!result.m_success)
    {
        result.m_errorMessage = "创建表失败";
    }

    return result;
}

// 解析并执行DROP TABLE语句
inline ExecuteResult ParseDropTable(const std::string& sql, MiniDatabase* db)
{
    ExecuteResult result;
    std::regex dropRegex(
        R"(^drop\s+table\s+(\w+)$)",
        std::regex::icase
    );

    std::smatch match;
    if (!std::regex_match(sql, match, dropRegex))
    {
        result.m_errorMessage = "DROP TABLE语句格式错误，正确格式: DROP TABLE 表名";
        return result;
    }

    std::string tableName = Trim(match[1]);
    if (!db->TableExists(tableName))
    {
        result.m_errorMessage = "表 " + tableName + " 不存在";
        return result;
    }

    result.m_success = db->DropTable(tableName);
    if (!result.m_success)
    {
        result.m_errorMessage = "删除表失败";
    }

    return result;
}

// 完整实现ParseAndExecute方法
ExecuteResult MiniDatabase::ParseAndExecute(const std::string& sql)
{
    ExecuteResult result;
    result.m_success = false;
    std::string sqlTrimmed = Trim(sql);
    if (sqlTrimmed.empty())
    {
        result.m_errorMessage = "空SQL语句";
        return result;
    }

    // 转换为小写用于判断语句类型
    std::string sqlLower = sqlTrimmed;
    std::transform(sqlLower.begin(), sqlLower.end(), sqlLower.begin(),
        [](unsigned char c) { return std::tolower(c); });

    try
    {
        if (sqlLower.substr(0, 6) == "select")
        {
            return ParseSelect(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 6) == "insert")
        {
            return ParseInsert(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 6) == "update")
        {
            return ParseUpdate(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 6) == "delete")
        {
            return ParseDelete(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 11) == "create table")
        {
            return ParseCreateTable(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 10) == "drop table")
        {
            return ParseDropTable(sqlTrimmed, this);
        }
        else if (sqlLower.substr(0, 5) == "begin")
        {
            // 处理BEGIN TRANSACTION
            result.m_success = BeginTransaction();
            if (!result.m_success)
            {
                result.m_errorMessage = "无法开始事务";
            }
        }
        else if (sqlLower.substr(0, 6) == "commit")
        {
            // 处理COMMIT
            result.m_success = CommitTransaction();
            if (!result.m_success)
            {
                result.m_errorMessage = "无法提交事务";
            }
        }
        else if (sqlLower.substr(0, 7) == "rollback")
        {
            // 处理ROLLBACK
            result.m_success = RollbackTransaction();
            if (!result.m_success)
            {
                result.m_errorMessage = "无法回滚事务";
            }
        }
        else
        {
            result.m_errorMessage = "不支持的SQL语句: " + sqlTrimmed;
        }
    }
    catch (const std::exception& e)
    {
        result.m_success = false;
        result.m_errorMessage = "执行SQL出错: " + std::string(e.what());
        LOG_ERROR("SQL执行异常: %s", e.what());
    }

    return result;
}

bool MiniDatabase::BeginTransaction()
{
    if (m_inTransaction)
    {
        LOG_WARN("已经在事务中");
        return false;
    }
    
    // 创建所有表的快照
    m_transactionSnapshots.clear();
    for (const auto& pair : m_tables)
    {
        // 这里简化处理，实际应该创建更深层次的拷贝
        m_transactionSnapshots[pair.first] = pair.second->Query();
    }
    
    m_inTransaction = true;
    LOG_INFO("事务开始");
    return true;
}

bool MiniDatabase::CommitTransaction()
{
    if (!m_inTransaction)
    {
        LOG_WARN("不在事务中，无法提交");
        return false;
    }
    
    m_transactionSnapshots.clear();
    m_inTransaction = false;
    
    // 提交时保存数据库
    Save();
    
    LOG_INFO("事务已提交");
    return true;
}

bool MiniDatabase::RollbackTransaction()
{
    if (!m_inTransaction)
    {
        LOG_WARN("不在事务中，无法回滚");
        return false;
    }
    
    // 恢复所有表的数据
    for (const auto& pair : m_transactionSnapshots)
    {
        Table* table = GetTable(pair.first);
        if (table)
        {
            table->Clear();
            for (const auto& record : pair.second)
            {
                table->Insert(record);
            }
        }
    }
    
    m_transactionSnapshots.clear();
    m_inTransaction = false;
    
    LOG_INFO("事务已回滚");
    return true;
}

bool MiniDatabase::Save()
{
    if (m_filePath.empty())
    {
        LOG_ERROR("保存数据库失败，未指定文件路径");
        return false;
    }
    
    try
    {
        // 创建数据库元数据
        Variant dbData; //VariantHash
        
        // 保存表结构
        VariantHash tableSchemas;
        for (const auto& pair : m_tables)
        {
            VariantVector fieldsData;
            for (const auto& field : pair.second->GetFields())
            {
                VariantHash fieldData;
                fieldData["name"] = field.m_name;
                fieldData["type"] = static_cast<int>(field.m_type);
                fieldData["isPrimaryKey"] = field.m_isPrimaryKey;
                fieldData["isNullable"] = field.m_isNullable;
                fieldData["defaultValue"] = field.m_defaultValue;
                fieldsData.push_back(fieldData);
            }
            tableSchemas[pair.first] = fieldsData;
        }
        dbData["schemas"] = std::move(tableSchemas);
        
        // 保存表数据
        VariantHash tableData;
        for (const auto& pair : m_tables)
        {
            tableData[pair.first] = pair.second->Query();
        }
        dbData["data"] = std::move(tableData);
        
        // 序列化并保存
        if (!dbData.SerializeToFile(m_filePath, VariantSerializeType::Binary))
        {
            LOG_ERROR("保存数据库到文件失败");
            return false;
        }
        
        LOG_INFO("成功将数据库保存到 %s，共 %zu 个表", m_filePath.c_str(), m_tables.size());
        return true;
    }
    catch (const std::exception& e)
    {
        LOG_ERROR("保存数据库失败: %s", e.what());
        return false;
    }
}

bool MiniDatabase::Load(const std::string& filePath)
{
    std::string loadPath = filePath.empty() ? m_filePath : filePath;
    if (loadPath.empty())
    {
        LOG_ERROR("加载数据库失败，未指定文件路径");
        return false;
    }
    
    try
    {
        Variant dbData;
        if (!dbData.DeserializeFromFile(loadPath, VariantSerializeType::Binary))
        {
            LOG_WARN("数据库文件不存在或无法读取，将创建新数据库");
            m_filePath = loadPath;
            return true;
        }
        
        if (dbData.Type() != VariantType::Hash)
        {
            LOG_ERROR("加载数据库失败，数据格式不正确");
            return false;
        }
        
        // 清除现有表
        m_tables.clear();
        
        // 加载表结构
        VariantHash &schemas = dbData["schemas"].RefValue<VariantHash>();
        for (const auto& pair : schemas)
        {
            const std::string& tableName = pair.first;
            const VariantVector& fieldsData = pair.second.ToVector();
            
            std::vector<FieldDefinition> fields;
            for (const auto& fieldData : fieldsData)
            {
                VariantHash& fieldHash = fieldData.RefValue<VariantHash>();

                std::string fieldName = fieldHash["name"].ToString();
                FieldType fieldType = static_cast<FieldType>(fieldHash["type"].ToInt());
                bool isPrimaryKey = fieldHash["isPrimaryKey"].ToBool();
                bool isNullable = fieldHash["isNullable"].ToBool();
                Variant defaultValue = fieldHash["defaultValue"];
                
                fields.emplace_back(fieldName, fieldType, isPrimaryKey, isNullable, defaultValue);
            }
            
            m_tables[tableName] = std::make_unique<Table>(tableName, fields);
        }
        
        // 加载表数据
        VariantHash tableData = dbData["data"].ToHash();
        for (const auto& pair : tableData)
        {
            const std::string& tableName = pair.first;
            const VariantVector& records = pair.second.ToVector();
            
            Table* table = GetTable(tableName);
            if (table)
            {
                for (auto& record : records)
                {
                    table->Insert(record.RefValue<VariantHash>());
                }
            }
        }
        
        m_filePath = loadPath;
        LOG_INFO("成功从 %s 加载数据库，共 %zu 个表", loadPath.c_str(), m_tables.size());
        return true;
    }
    catch (const std::exception& e)
    {
        LOG_ERROR("加载数据库失败: %s", e.what());
        return false;
    }
}
}
    
